import com.mysql.jdbc.jdbc2.optional.MysqlDataSource;

import javax.sql.DataSource;
import javax.xml.transform.Result;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Scanner;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: lenovo
 * Date: 2022-08-09
 * Time: 22:11
 */
public class MySQLSelect {
    public static void main(String[] args) throws SQLException {
        //1.
        DataSource dataSource = new MysqlDataSource();
        ((MysqlDataSource)dataSource).setURL("jdbc:mysql://127.0.0.1:3306/java105?characterEncoding=utf8&useSSL=false");
        ((MysqlDataSource)dataSource).setUser("root");
        ((MysqlDataSource)dataSource).setPassword("");
        //2.
        Connection connection = dataSource.getConnection();
        System.out.println(connection);
        //3.
        String sql = "select * from student";
        PreparedStatement statement = connection.prepareStatement(sql);
//        String sql = "select * from student where id = ?";
//        PreparedStatement statement = connection.prepareStatement(sql);
//        statement.setInt(1,1);
        //4.
        ResultSet resultSet = statement.executeQuery();

        //5.遍历结果集合
        while (resultSet.next()) {
            //每次循环,就能够获取到resultset中的一行,进一步就可以拿到每一行的每一列
            //getXXX也是有一系列方法的,会根据要取的数据类型,来灵活决策
            int id = resultSet.getInt("id");
            String name = resultSet.getString("name");
            System.out.println("id =" + id + ",name =" + name);
        }

            //6.释放相关资源
            resultSet.close();
            statement.close();
            connection.close();
        }
    }

